package cc.sheji.Service;


import cc.sheji.domain.InvitationList;
import cc.sheji.domain.InvitationListDto;
import cc.sheji.domain.User;
import cc.sheji.domain.UserFocus;
import cc.sheji.reposity.InvitationListRepository;
import cc.sheji.reposity.UserRepository;
import cc.sheji.util.QueryHelp;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class InvitationListService {


    @Autowired
    InvitationListRepository invitationListRepository;
    @Autowired
    UserRepository userRepository;


    public List<User> invitationUserList(Pageable pageable){
        Map<String,Long> criteria=new HashMap<>();
        criteria.put("invitationUser", StpUtil.getLoginIdAsLong());
        Page<InvitationList> page= invitationListRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        List<User> result=new ArrayList<>();
        if(page.hasContent())
        {
            List<Long> userIds=page.getContent().stream().map(InvitationList::getInvitees).collect(Collectors.toList());
            result= (List<User>) userRepository.findAllById(userIds);
        }

        return result;
    }


    public List<InvitationList> invitationList(Pageable pageable){
        Map<String,Long> criteria=new HashMap<>();
        criteria.put("invitationUser", StpUtil.getLoginIdAsLong());
        Page<InvitationList> page= invitationListRepository.findAll((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);

        if(page.hasContent())
            return page.getContent();
        return new ArrayList<>();
    }


    public Map<String,Long> countInvitation(){
        Map<String,Long> criteria=new HashMap<>();
        criteria.put("invitationUser", StpUtil.getLoginIdAsLong());
        long userCnt=invitationListRepository.count((root, criteriaQuery, criteriaBuilder) ->
                QueryHelp.getPredicate(root, criteria, criteriaBuilder));

        long awardTotal=invitationListRepository.awardTotal(StpUtil.getLoginIdAsLong());

        Map<String,Long> result=new HashMap<>();
        result.put("userTotal", userCnt);
        result.put("awardTotal", awardTotal);
        return result;
    }
}
